package com.cqc.customdialog;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;

import java.lang.reflect.Field;
import java.util.Calendar;

import es.dmoral.toasty.Toasty;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private Context context;
    private Button btn1;
    private Button btn2;
    private Button btn3;
    private Button btn4;
    private Button btn5;
    private Button btn6;
    private Button btn7;
    private Button btn8;
    private String date;
    private String time;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        btn1 = (Button) findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createDatePickerDialogNoSetButton();
            }
        });

        btn2 = (Button) findViewById(R.id.btn2);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createTimePickerDialogNoSetButton();
            }
        });

        btn3 = (Button) findViewById(R.id.btn3);
        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createDatePickerDialogWithSetButton();
            }
        });

        btn4 = (Button) findViewById(R.id.btn4);
        btn4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createTimePickerDialogWithSetButton();
            }
        });

        btn5 = (Button) findViewById(R.id.btn5);
        btn5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createDateAndTimePickerDialog();
            }
        });

        btn6 = (Button) findViewById(R.id.btn6);
        btn6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, MainActivity2.class));
            }
        });

        btn7 = (Button) findViewById(R.id.btn7);
        btn7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, MainActivity3.class));
            }
        });

        btn8 = (Button) findViewById(R.id.btn8);
        btn8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createDatePickerDialogWithSetButton2();
            }
        });
    }

    private void createDatePickerDialogNoSetButton() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePickerDialog = new DatePickerDialog(context, onDateSetListener, year, month, dayOfMonth);

        datePickerDialog.setCanceledOnTouchOutside(false);
        datePickerDialog.setCancelable(false);
        datePickerDialog.show();
    }

    private void createTimePickerDialogNoSetButton() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        MyOnTimeSetListener timeSetListener = new MyOnTimeSetListener();

        TimePickerDialog dialog = new TimePickerDialog(context, timeSetListener, hour, minute, true);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
    }


    /**
     * DatePickerDialog  使用setButton（。。。）
     */
    private void createDatePickerDialogWithSetButton() {
        //android.icu.util.Calendar API>=24
//        Calendar calendar = Calendar.getInstance();
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        MyOnDateSetListener onDateSetListener = new MyOnDateSetListener();
        //可以不传参数OnDateSetListener， 第2个参数： int themeResId, 第三个参数：OnDateSetListener
        final DatePickerDialog dialog = new DatePickerDialog(context, 0, null, year, month, day);

        dialog.setButton("自定义Button:确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog2, int which) {
                DatePicker datePicker = dialog.getDatePicker();
                int year = datePicker.getYear();
                int month = datePicker.getMonth() + 1;
                int dayOfMonth = datePicker.getDayOfMonth();
                Log.d(TAG, "日期：" + year + "年" + month + "月" + dayOfMonth + "日");
            }
        });
        dialog.setButton2("自定义Button:取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.d(TAG, "取消" + ",which=" + which);
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
    }

    //无效，重写了setButton(...)方法，那么OnTimeSetListener就无效了
//        dialog.setButton("确定", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                Log.d(TAG, "确定" + ",which=" + which);//which = -2
//            }
//        });
//        dialog.setButton2("取消", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                Log.d(TAG, "取消" + ",which=" + which);//which = -1
//            }
//        });

    /**
     * TimePickerDialog
     */
    private void createTimePickerDialogWithSetButton() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        MyOnTimeSetListener timeSetListener = new MyOnTimeSetListener();
        TimePickerDialog dialog = new TimePickerDialog(context, timeSetListener, hour, minute, true);
        //有效方法，第2个参数不传OnClickListener,直接传入dialog本身
        dialog.setButton("自定义Button:确定", dialog);
        dialog.setButton2("自定义Button:取消", dialog);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
    }


    private void createDateAndTimePickerDialog() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        final DatePickerDialog dialog = new DatePickerDialog(context, null, year, month, day);
        dialog.setButton("选择时间", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog2, int which) {
                DatePicker datePicker = dialog.getDatePicker();
                int year1 = datePicker.getYear();
                int month1 = datePicker.getMonth();
                int dayOfMonth = datePicker.getDayOfMonth();

                Calendar calendar = Calendar.getInstance();
                int currentYear = calendar.get(Calendar.YEAR);
                int currentMonth = calendar.get(Calendar.MONTH);
                int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
                if (currentYear <= year1 && currentMonth <= month1 && currentDay <= dayOfMonth) {
                    Log.d(TAG, "日期：" + year1 + "年" + month1 + "月" + dayOfMonth + "日");
                    date = year1 + "年" + month1 + "月" + dayOfMonth + "日";
                    Log.d(TAG, date.toString());
                    createSingleChoiceDialog();
                } else {
                    Toasty.error(context, "不能小于当前日期").show();
                    Log.d(TAG, "不能小于当前日期");
                    try {
                        Field field = dialog.getClass().getSuperclass().getSuperclass().getSuperclass()
                                .getDeclaredField("mShowing");
                        field.setAccessible(true);
                        // 将mShowing变量设为false，表示对话框已关闭
                        field.set(dialog, false);
                        dialog.dismiss();
                    } catch (Exception e) {
                    }
                }
            }
        });
        dialog.setButton2("", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.d(TAG, "确定" + ",which=" + which);//which = -2
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
    }

    private void createSingleChoiceDialog() {
        final String[] times = getResources().getStringArray(R.array.times);
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("选择时间")
                .setCancelable(false)
                .setIcon(android.R.drawable.ic_dialog_info)
                .setSingleChoiceItems(times, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        time = times[which];//which 在array中的position
                        Log.d(TAG, "time=" + time);
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.d(TAG, "日期+时间=" + date + "  " + time);
                    }
                })

                .setNegativeButton("选择日期", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        createDateAndTimePickerDialog();
                    }
                });
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }


    private class MyOnTimeSetListener implements TimePickerDialog.OnTimeSetListener {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            Log.d(TAG, "时间：" + hourOfDay + "时" + minute + "分");
        }
    }


    private class MyOnDateSetListener implements DatePickerDialog.OnDateSetListener {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            Log.d(TAG, "日期：" + year + "年" + month + "月" + dayOfMonth + "日");
            date = year + "年" + month + "月" + dayOfMonth + "日";
        }
    }

    private DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            Log.d(TAG, "日期：" + year + "年" + month + "月" + dayOfMonth + "日");
        }
    };


    /**
     * DatePickerDialog  使用setButton（。。。）
     */
    DatePickerDialog dialog;
    private void createDatePickerDialogWithSetButton2() {
        //android.icu.util.Calendar API>=24
//        Calendar calendar = Calendar.getInstance();
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
         dialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                Log.d(TAG, "日期：" + year + "年" + month + "月" + dayOfMonth + "日");
                Toasty.info(context, "日期：" + year + "," + month + "," + dayOfMonth).show();
                dialogDisplayOpear(false);// dialog显示控制-不关闭
            }

            private void dialogDisplayOpear(boolean isDisplay) {
                try {
                    Field field = dialog.getClass().getSuperclass().getSuperclass().getSuperclass()
                            .getDeclaredField("mShowing");
                    field.setAccessible(true);
                    // 将mShowing变量设为false，表示对话框已关闭
                    field.set(dialog, isDisplay);
                    dialog.dismiss();
                } catch (Exception e) {
                }
            }

        }, year, month, day);

//        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", dialog);
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", dialog);
        dialog.setButton(DialogInterface.BUTTON_NEUTRAL, "中立", dialog);


//        dialog.setButton(DialogInterface.BUTTON1,"Button1",dialog);
//        dialog.setButton(DialogInterface.BUTTON2,"Button2",dialog);
//        dialog.setButton(DialogInterface.BUTTON3,"Button3",dialog);

//        dialog.setButton3("btn3",dialog);


        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
    }

    //无效，重写了setButton(...)方法，那么OnTimeSetListener就无效了
//        dialog.setButton("确定", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                Log.d(TAG, "确定" + ",which=" + which);//which = -2
//            }
//        });
//        dialog.setButton2("取消", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                Log.d(TAG, "取消" + ",which=" + which);//which = -1
//            }
//        });

}
